package cn.com.redis;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * 分布式场景下的redis连接工具类
 * 
 * @author hardinxu
 *
 */
public class RedisDistributionConnectionTool {
	private static Logger _log = LogManager.getLogger(RedisDistributionConnectionTool.class.getName());

	private ShardedJedisPool pool = null;
	private ShardedJedis activeRedisClient = null;

	public RedisDistributionConnectionTool() {
		this.pool = RedisInitializer.shardedJedisPool;
	}

	public synchronized ShardedJedis getRedisClient() {
		this.activeRedisClient = this.pool.getResource();
		return this.activeRedisClient;
	}

	public void returnClientResource() {
		if (null != this.activeRedisClient) {
			this.pool.returnResource(this.activeRedisClient);
		}
	}

	public void returnBrokenClientResource() {
		if (null != this.activeRedisClient) {
			this.pool.returnBrokenResource(this.activeRedisClient);
		}
	}

	public void returnClientResource(ShardedJedis shardedJedisClient) {
		this.pool.returnResource(shardedJedisClient);
	}

	public void returnBrokenClientResource(ShardedJedis shardedJedisClient) {
		this.pool.returnBrokenResource(shardedJedisClient);
	}

	protected void finalize() {
		try {
			// this.pool.destroy();
			super.finalize();
		} catch (Throwable e) {
			e.printStackTrace();
			_log.error("Release Redis connection pool failure. Message:" + e.getMessage());
		}
	}

}
